<!-- views/user/UserProfile.vue -->
<template>
  <div class="user-profile">
    <!-- 返回按钮 -->
    <div class="back-button">
      <button @click="goBack" class="back-btn">
        <span>← 返回主界面</span>
      </button>
    </div>

    <div class="profile-container">
      <div class="profile-header">
        <div class="avatar-section">
          <div class="user-avatar-large">
            {{ getUserInitial(authStore.user) }}
          </div>
          <h2>{{ getUserDisplayName(authStore.user) }}</h2>
          <p class="user-role">{{ getDisplayRole(authStore.user?.role) }}</p>
        </div>
      </div>

      <div class="profile-content">
        <!-- 基本信息表单 -->
        <div class="form-section">
          <h3>基本信息</h3>
          <form @submit.prevent="handleProfileUpdate" class="profile-form">
            <div class="form-group">
              <label for="username">用户名</label>
              <input
                  id="username"
                  v-model="profileForm.username"
                  type="text"
                  placeholder="请输入用户名"
              >
            </div>

            <div class="form-group">
              <label for="farmName">农场名称</label>
              <input
                  id="farmName"
                  v-model="profileForm.farmName"
                  type="text"
                  placeholder="请输入农场名称"
              >
            </div>

            <button
                type="submit"
                class="save-btn"
                :disabled="authStore.isLoading"
            >
              {{ authStore.isLoading ? '保存中...' : '保存更改' }}
            </button>
          </form>
        </div>

        <!-- 密码修改 -->
        <div class="form-section">
          <h3>修改密码</h3>
          <form @submit.prevent="handlePasswordChange" class="password-form">
            <div class="form-group">
              <label for="newPassword">新密码</label>
              <input
                  id="newPassword"
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码"
              >
            </div>

            <div class="form-group">
              <label for="confirmPassword">确认新密码</label>
              <input
                  id="confirmPassword"
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
              >
            </div>

            <button
                type="submit"
                class="save-btn"
                :disabled="authStore.isLoading"
            >
              {{ authStore.isLoading ? '修改中...' : '修改密码' }}
            </button>
          </form>

          <div class="password-tips">
            <p>💡 提示：修改密码后需要重新登录</p>
          </div>
        </div>

        <!-- 账户注销 -->
        <div class="form-section danger-section">
          <h3>账户操作</h3>
          <div class="danger-actions">
            <p class="danger-warning">
              ⚠️ 此操作不可逆，请谨慎操作
            </p>
            <button
                @click="showDeleteConfirm = true"
                class="delete-btn"
                :disabled="authStore.isLoading"
            >
              {{ authStore.isLoading ? '处理中...' : '注销账户' }}
            </button>
          </div>
        </div>

        <!-- 错误提示 -->
        <div v-if="authStore.error" class="error-message">
          {{ authStore.error }}
        </div>

        <!-- 成功提示 -->
        <div v-if="successMessage" class="success-message">
          {{ successMessage }}
        </div>
      </div>
    </div>

    <!-- 注销确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay">
      <div class="modal-content">
        <h3>确认注销账户</h3>
        <div class="modal-body">
          <p class="warning-text">⚠️ 此操作将永久删除您的账户，包括所有相关数据。</p>
          <p class="warning-text">一旦注销，将无法恢复！</p>

          <div class="verification-input">
            <label for="confirmText">请输入您的手机号以确认：</label>
            <input
                id="confirmText"
                v-model="deleteConfirmText"
                type="text"
                placeholder="请输入您的手机号"
                class="confirm-input"
            >
            <p class="hint-text">当前手机号：{{ authStore.user?.phone }}</p>
          </div>
        </div>
        <div class="modal-actions">
          <button
              @click="showDeleteConfirm = false"
              class="cancel-btn"
              :disabled="authStore.isLoading"
          >
            取消
          </button>
          <button
              @click="handleDeleteAccount"
              class="confirm-delete-btn"
              :disabled="!isDeleteConfirmed || authStore.isLoading"
          >
            {{ authStore.isLoading ? '注销中...' : '确认注销' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const successMessage = ref('')
const showDeleteConfirm = ref(false)
const deleteConfirmText = ref('')

// 表单数据
const profileForm = reactive({
  username: '',
  farmName: ''
})

// 修改密码表单数据
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 计算属性：检查删除确认输入是否正确
const isDeleteConfirmed = computed(() => {
  return deleteConfirmText.value === authStore.user?.phone
})

// 安全获取用户首字母
const getUserInitial = (user) => {
  if (!user) return 'U'
  const name = user.phone || user.username || '用户'
  return name.charAt(0).toUpperCase()
}

// 安全获取用户显示名称
const getUserDisplayName = (user) => {
  if (!user) return '未知用户'
  return user.phone || user.username || '未知用户'
}

// 角色显示映射
const getDisplayRole = (role) => {
  const roleDisplayMap = {
    'ROLE_ADMIN': '管理员',
    'USER': '用户'
  }
  return roleDisplayMap[role] || '用户'
}

// 返回主界面
const goBack = () => {
  router.push('/dashboard/smart-home')
}

// 初始化表单数据
const initFormData = () => {
  if (authStore.user) {
    profileForm.username = authStore.user.username || authStore.user.phone || ''
    profileForm.farmName = authStore.user.farmName || ''

    console.log('📋 初始化表单数据:', {
      username: profileForm.username,
      farmName: profileForm.farmName
    })
  }
}

// 处理资料更新
const handleProfileUpdate = async () => {
  console.log('🔄 处理资料更新:', profileForm)

  // 由于后端没有专门的用户资料更新接口，这里暂时模拟成功
  successMessage.value = '资料更新功能暂未实现'
  setTimeout(() => {
    successMessage.value = ''
  }, 3000)
}

// 处理密码修改
const handlePasswordChange = async () => {
  console.log('🔐 开始处理密码修改')

  // 验证密码一致性
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    authStore.error = '两次输入的密码不一致'
    return
  }

  if (!passwordForm.newPassword) {
    authStore.error = '请输入新密码'
    return
  }

  if (passwordForm.newPassword.length < 6) {
    authStore.error = '密码长度至少6位'
    return
  }

  console.log('🔐 密码修改参数:')
  console.log('   - 用户手机号:', authStore.user?.phone)
  console.log('   - 新密码长度:', passwordForm.newPassword.length)

  try {
    const result = await authStore.changePassword(authStore.user.phone, passwordForm.newPassword)

    if (result.success) {
      successMessage.value = result.message || '密码修改成功！'
      console.log('✅ 密码修改成功')

      // 清空密码表单
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''

      // 清除错误信息
      authStore.error = ''

      setTimeout(() => {
        successMessage.value = ''
      }, 3000)
    } else {
      authStore.error = result.message
      console.log('❌ 密码修改失败:', result.message)
    }
  } catch (error) {
    console.error('🚨 密码修改异常:', error)
    authStore.error = '网络错误，请稍后重试'
  }
}

// 处理账户注销 - 关键修改：使用 deleteUser 而不是 deleteAccount
const handleDeleteAccount = async () => {
  console.log('🗑️ 开始注销账户:', authStore.user?.phone)

  if (!isDeleteConfirmed.value) {
    authStore.error = '请输入正确的手机号以确认注销'
    return
  }

  try {
    // 关键修改：改为调用 deleteUser 方法
    const result = await authStore.deleteUser(authStore.user.phone)

    if (result.success) {
      console.log('✅ 账户注销成功')
      successMessage.value = '账户已成功注销'

      // 跳转到登录页面
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    } else {
      authStore.error = result.message
      console.log('❌ 账户注销失败:', result.message)
      showDeleteConfirm.value = false
    }
  } catch (error) {
    console.error('🚨 账户注销异常:', error)
    authStore.error = '网络错误，请稍后重试'
    showDeleteConfirm.value = false
  }
}

onMounted(() => {
  console.log('🚀 UserProfile 组件挂载')
  console.log('👤 当前用户信息:', authStore.user)

  // 修复：移除不存在的 fetchUserProfile 调用，直接初始化表单数据
  initFormData()
})
</script>

<style scoped>
.user-profile {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.back-btn {
  background: linear-gradient(135deg, #48bb78, #2d5a27);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.back-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(72, 187, 120, 0.3);
}

.profile-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.profile-header {
  background: linear-gradient(135deg, #2d5a27, #1e3c1e);
  color: white;
  padding: 40px 30px;
  text-align: center;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-avatar-large {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #48bb78, #2d5a27);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 15px;
  border: 4px solid rgba(255, 255, 255, 0.2);
}

.user-role {
  opacity: 0.8;
  margin-top: 5px;
}

.profile-content {
  padding: 30px;
}

.form-section {
  margin-bottom: 40px;
}

.form-section h3 {
  color: #2d5a27;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e2e8f0;
}

.danger-section h3 {
  color: #e53e3e;
  border-bottom-color: #fed7d7;
}

.profile-form,
.password-form {
  display: grid;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-weight: 600;
  margin-bottom: 8px;
  color: #2d3748;
}

.form-group input {
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #48bb78;
  box-shadow: 0 0 0 3px rgba(72, 187, 120, 0.1);
}

.save-btn {
  background: linear-gradient(135deg, #48bb78, #2d5a27);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s;
  justify-self: start;
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(72, 187, 120, 0.3);
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 危险操作区域样式 */
.danger-actions {
  padding: 20px;
  background: #fff5f5;
  border: 1px solid #fed7d7;
  border-radius: 8px;
}

.danger-warning {
  color: #c53030;
  margin-bottom: 15px;
  font-weight: 500;
}

.delete-btn {
  background: linear-gradient(135deg, #e53e3e, #c53030);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s;
}

.delete-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(229, 62, 62, 0.3);
}

.delete-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  max-width: 500px;
  width: 90%;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
}

.modal-content h3 {
  color: #e53e3e;
  margin-bottom: 20px;
  text-align: center;
}

.modal-body {
  margin-bottom: 25px;
}

.warning-text {
  color: #e53e3e;
  margin-bottom: 10px;
  text-align: center;
  font-weight: 500;
}

.verification-input {
  margin-top: 20px;
}

.verification-input label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #2d3748;
}

.confirm-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s;
}

.confirm-input:focus {
  outline: none;
  border-color: #e53e3e;
  box-shadow: 0 0 0 3px rgba(229, 62, 62, 0.1);
}

.hint-text {
  font-size: 12px;
  color: #718096;
  margin-top: 5px;
}

.modal-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.cancel-btn {
  background: #a0aec0;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.cancel-btn:hover:not(:disabled) {
  background: #718096;
}

.confirm-delete-btn {
  background: linear-gradient(135deg, #e53e3e, #c53030);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s;
}

.confirm-delete-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(229, 62, 62, 0.3);
}

.confirm-delete-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.error-message {
  background: #fed7d7;
  color: #c53030;
  padding: 12px 16px;
  border-radius: 6px;
  margin-top: 20px;
}

.success-message {
  background: #c6f6d5;
  color: #276749;
  padding: 12px 16px;
  border-radius: 6px;
  margin-top: 20px;
}

.password-tips {
  margin-top: 10px;
  padding: 10px;
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  font-size: 14px;
  color: #0369a1;
}

.password-tips p {
  margin: 0;
}

@media (max-width: 768px) {
  .user-profile {
    padding: 10px;
  }

  .profile-content {
    padding: 20px;
  }

  .modal-content {
    padding: 20px;
  }

  .modal-actions {
    flex-direction: column;
  }
}
</style>